<template>
    <div class="menu" :class="{ 'collapsed': isCollapse }">
        <div class="collapse-btn" @click="toggleCollapse">
            <i :class="isCollapse ? 'el-icon-s-unfold' : 'el-icon-s-fold'"></i>
        </div>
        <el-menu
            :default-active="activeMenu"
            class="el-menu-vertical-demo"
            :collapse="isCollapse"
            :router="true"
            :unique-opened="true"
            background-color="#333744"
            text-color="#fff"
            active-text-color="#ffd04b"
            @open="handleOpen"
            @close="handleClose"
            @select="handleSelect"
            ref="menu"
        >
            <template v-for="(item, index) in listData">
                <el-submenu v-if="item.children && item.children.length > 0" :index="item.url"
                            :data-index="item.menu_id" :key="index"
                            @click.native.stop="handleSubmenuClick(item, $event)">
                    <template slot="title">
                        <img v-if="item.icon" :src="item.icon" alt="" style="width: 20px; height: 20px;">
                        <i v-else-if="item.code" :class="item.code"></i>
                        <i v-else :class="getDefaultIcon(item.name)"></i>
                        <span :data-path="item.url" style="margin-left: 5px;">{{ item.name }}</span>
                    </template>
                    <el-menu-item v-for="(child, childIndex) in item.children" :key="`${index}-${childIndex}`"
                                  :index="child.url" :route="{ path: child.url }"
                                  @click="handleMenuItemClick(child, $event)" style="padding-left: 50px !important;"
                                  :disabled="child.disabled">
                        <i v-if="child.code" :class="child.code"></i>
                        <i v-else :class="getDefaultIcon(child.name)"></i>
                        <span :data-path="child.url">{{ child.name }}</span>
                    </el-menu-item>
                </el-submenu>
                <el-menu-item v-else :index="item.url" :key="index" :route="{ path: item.url }"
                              @click="handleMenuItemClick(item, $event)" :disabled="item.disabled">
                    <img v-if="item.icon" :src="item.icon" alt="" style="width: 20px; height: 20px;">
                    <i v-else-if="item.code" :class="item.code"></i>
                    <i v-else :class="getDefaultIcon(item.name)"></i>
                    <span :data-path="item.url" style="margin-left: 5px;">{{ item.name }}</span>
                </el-menu-item>
            </template>
        </el-menu>
    </div>
</template>

<script>
import {mapState} from 'vuex';

export default {
    data() {
        return {
            active: '/dashboard',
            isCollapse: false,
            listData: [],
            showButtonText: {},
            openedMenus: new Set(), // 用于跟踪展开的菜单
            touchStartX: 0,
            touchEndX: 0,
            // 基础类别映射，用于智能分配图标
            baseCategories: [
                // 系统相关
                { keywords: ['系统'], icon: 'el-icon-setting' },
                // 商品相关
                { keywords: ['商品'], icon: 'el-icon-goods' },
                // 运营相关
                { keywords: ['运营'], icon: 'el-icon-s-operation' },
                // 用户相关
                { keywords: ['用户'], icon: 'el-icon-user' },
                // 审核相关
                { keywords: ['审核'], icon: 'el-icon-s-check' },
                // 订单相关
                { keywords: ['订单'], icon: 'el-icon-s-order' },
                // 数据相关
                { keywords: ['全部数据', '数据中心'], icon: 'el-icon-s-data' },
                // 更新记录
                { keywords: ['更新'], icon: 'el-icon-document' },
                // 其他常用
                { keywords: ['管理'], icon: 'el-icon-s-management' },
                { keywords: ['设置', '配置'], icon: 'el-icon-setting' },
                { keywords: ['记录', '日志', '历史'], icon: 'el-icon-document' }
            ],
            // 精确匹配表 - 为特定菜单名称提供精确图标
            exactMatches: {
                '系统设置': 'el-icon-setting', 
                '商品管理': 'el-icon-goods',
                '运营管理': 'el-icon-s-operation',
                '用户管理': 'el-icon-user',
                '审核管理': 'el-icon-s-check',
                '订单管理': 'el-icon-s-order',
                '全部数据': 'el-icon-s-data',
                '更新记录': 'el-icon-document',
                '数据中心': 'el-icon-s-marketing'
            },
            // 缓存已生成的图标，提高性能
            iconCache: {}
        };
    },
    computed: {
        ...mapState(['menuList']),
        isMobile() {
            return window.innerWidth <= 768;
        },
        activeMenu() {
            // 只要是店铺装修相关页面，菜单高亮都在 /shopDecoration/shopDecoration
            if (this.$route.path.startsWith('/shopDecoration/')) {
                return '/shopDecoration/shopDecoration';
            }
            return this.$route.path;
        }
    },
    created() {
    },
    mounted() {
        this.initData();
        this.active = this.$route.path;

        // 检测是否为移动设备，如果是则默认折叠菜单
        if (this.isMobile) {
            this.isCollapse = true;
        }

        // 添加触摸事件监听器
        document.addEventListener('touchstart', this.handleTouchStart);
        document.addEventListener('touchend', this.handleTouchEnd);

        // 监听窗口大小变化
        window.addEventListener('resize', this.handleResize);
    },
    watch: {
        '$route.path'(newPath) {
            this.active = newPath;
        }
    },
    beforeDestroy() {
        // 移除事件监听器
        document.removeEventListener('touchstart', this.handleTouchStart);
        document.removeEventListener('touchend', this.handleTouchEnd);
        window.removeEventListener('resize', this.handleResize);
    },
    methods: {
        getDefaultIcon(name) {
            // 如果名称为空，返回默认图标
            if (!name) return 'el-icon-menu';

            // 检查缓存中是否已有此名称的图标
            if (this.iconCache[name]) {
                return this.iconCache[name];
            }

            // 1. 尝试精确匹配
            if (this.exactMatches[name]) {
                this.iconCache[name] = this.exactMatches[name];
                return this.exactMatches[name];
            }

            // 2. 尝试关键词匹配
            for (const category of this.baseCategories) {
                for (const keyword of category.keywords) {
                    if (name.includes(keyword)) {
                        this.iconCache[name] = category.icon;
                        return category.icon;
                    }
                }
            }

            // 3. 根据第一个字符分配固定图标
            const firstChar = name.charAt(0);
            const iconMapping = {
                '系': 'el-icon-setting',
                '商': 'el-icon-goods',
                '运': 'el-icon-s-operation',
                '用': 'el-icon-user',
                '审': 'el-icon-s-check',
                '订': 'el-icon-s-order',
                '全': 'el-icon-s-data',
                '更': 'el-icon-document',
                '数': 'el-icon-s-marketing'
            };

            if (iconMapping[firstChar]) {
                this.iconCache[name] = iconMapping[firstChar];
                return iconMapping[firstChar];
            }

            // 4. 根据名称生成一个一致的图标
            const icons = [
                'el-icon-menu',
                'el-icon-s-grid',
                'el-icon-s-management',
                'el-icon-s-custom',
                'el-icon-s-marketing',
                'el-icon-s-tools',
                'el-icon-s-shop',
                'el-icon-s-platform'
            ];

            const charCode = name.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
            const index = charCode % icons.length;

            this.iconCache[name] = icons[index];
            return icons[index];
        },

        initData() {
            this.$http.get('/admin/AuthNode/getMenu', {params: this.params}).then(result => {
                if (result.code === 200) {
                    if(Object.keys(result.data)[0] === "39" && this.$router.history.current.path !== "/order/orderShichang"){
                        this.$router.push("/order/orderShichang")
                    }
                    // 直接使用返回的数据数组
                    this.listData = Array.isArray(result.data) ? result.data : Object.values(result.data);

                    // 添加后台菜单演示数据（如果API返回的为空）
                    if (this.listData.length === 0) {
                        this.listData = this.getMenuDemo();
                    }

                    // 递归处理所有层级的菜单项，并自动分配图标
                    const processMenuItems = (items) => {
                        items.forEach(item => {
                            this.showButtonText[item.menu_id] = item.state === 0;

                            // 如果没有code字段，根据名称分配icon
                            if (!item.icon) {
                                item.code = this.getDefaultIcon(item.name);
                            }

                            if (item.children && item.children.length > 0) {
                                processMenuItems(item.children);
                            }
                        });
                    };

                    processMenuItems(this.listData);

                    // 强制刷新菜单
                    this.$nextTick(() => {
                        if (this.$refs.menu) {
                            this.$forceUpdate();
                        }
                    });
                } else {
                    this.$message.error("登录失效");
                    this.$router.push("/login");
                }
            });
        },

        // 如果API无法返回数据，使用这个演示数据
        getMenuDemo() {
            return [
                { name: '系统设置', url: '/system', menu_id: '1' },
                { name: '商品管理', url: '/goods', menu_id: '2' },
                { name: '运营管理', url: '/operation', menu_id: '3' },
                { name: '用户管理', url: '/user', menu_id: '4' },
                { name: '审核管理', url: '/audit', menu_id: '5' },
                { name: '订单管理', url: '/order', menu_id: '6' },
                { name: '全部数据', url: '/alldata', menu_id: '7' },
                { name: '更新记录', url: '/updates', menu_id: '8' },
                { name: '数据中心', url: '/datacenter', menu_id: '9',
                    children: [
                        { name: '余额明细', url: '/datacenter/balance', menu_id: '91' },
                        { name: '分红明细', url: '/datacenter/bonus', menu_id: '92' },
                        { name: '业绩排名', url: '/datacenter/performance', menu_id: '93' },
                        { name: '我的补贴', url: '/datacenter/subsidy', menu_id: '94' },
                        { name: '补贴余额', url: '/datacenter/balance', menu_id: '95' }
                    ]
                }
            ];
        },

        toggleCollapse() {
            this.isCollapse = !this.isCollapse;
        },
        handleTouchStart(e) {
            this.touchStartX = e.changedTouches[0].screenX;
        },
        handleTouchEnd(e) {
            this.touchEndX = e.changedTouches[0].screenX;
            this.handleSwipe();
        },
        handleSwipe() {
            const swipeDistance = this.touchEndX - this.touchStartX;
            const threshold = 100; // 滑动阈值

            if (this.isMobile) {
                // 从左向右滑动展开菜单
                if (swipeDistance > threshold && this.isCollapse) {
                    this.isCollapse = false;
                }
                // 从右向左滑动收起菜单
                else if (swipeDistance < -threshold && !this.isCollapse) {
                    this.isCollapse = true;
                }
            }
        },
        handleResize() {
            // 响应窗口大小变化
            if (window.innerWidth <= 768 && !this.isCollapse) {
                this.isCollapse = true;
            }
        },
        handleSelect(e) {
        },
        handleOpen(index) {
            // 关闭其他已展开的菜单
            const openedMenus = this.$refs.menu.openedMenus;
            openedMenus.forEach(menu => {
                if (menu !== index) {
                    this.$refs.menu.closeMenu(menu);
                }
            });

            // 新增逻辑：跳转到第一个子项
            const targetMenu = this.listData.find(item => item.url === index);
            if (targetMenu && targetMenu.children && targetMenu.children.length > 0) {
                const firstEnabledChild = targetMenu.children.find(child => !child.disabled);
                if (firstEnabledChild) {
                    this.active = firstEnabledChild.url;
                    this.$router.push(firstEnabledChild.url);
                }
            }
        },
        handleClose(index) {
            // 清除已关闭的菜单记录
            this.openedMenus.delete(index);
        },
        handleSubmenuClick(item, event) {
            if (item.children && item.children.length > 0) {
                const isOpen = this.openedMenus.has(item.url);
                if (isOpen) {
                    this.openedMenus.delete(item.url);
                    this.$nextTick(() => {
                        const submenu = this.$refs.menu.$el.querySelector(`[data-index="${item.menu_id}"]`);
                        if (submenu) {
                            submenu.click();
                        }
                    });
                } else {
                    // 关闭其他已展开的菜单
                    this.openedMenus.forEach(url => {
                        this.$nextTick(() => {
                            const submenu = this.$refs.menu.$el.querySelector(`[data-index="${url}"]`);
                            if (submenu) {
                                submenu.click();
                            }
                        });
                    });
                    this.openedMenus.clear();
                    this.openedMenus.add(item.url);
                    this.$nextTick(() => {
                        const submenu = this.$refs.menu.$el.querySelector(`[data-index="${item.menu_id}"]`);
                        if (submenu) {
                            submenu.click();
                        }
                    });
                }
            }
        },
        handleMenuItemClick(item, event) {
            if (!item.children || item.children.length === 0) {
                this.active = item.url; // 保证手动点击也能高亮
                // 在移动设备上点击菜单项后自动收起菜单
                if (this.isMobile) {
                    this.isCollapse = true;
                }
            }
        }
    }
};
</script>

<style lang="less" scoped>
.menu {
    background: #333744;
    overflow: hidden;
    border-radius: 0 0.9375rem 0 0;
    position: relative;
    transition: all 0.3s;

    .collapse-btn {
        height: 3rem;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        padding: 0 1rem;
        color: white;
        cursor: pointer;
        background-color: #2b2f3a;
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);

        i {
            font-size: 1.5rem;
            transition: all 0.3s;

            &:hover {
                color: #ffd04b;
                transform: scale(1.1);
            }
        }
    }

    .el-menu-vertical-demo:not(.el-menu--collapse) {
        width: 12.5rem;
    }

    ::v-deep(.el-menu) {
        border-right: none;

        .el-submenu {
            .el-submenu__title {
                i.icon {
                    width: 1.125rem;
                    height: 1rem;
                }

                img {
                    width: 1.25rem;
                    height: 1.25rem;
                    margin-right: 0.3125rem;
                }

                span {
                    font-size: 0.875rem;
                }

                i[class^="el-icon-"] {
                    margin-right: 5px;
                    width: 24px;
                    text-align: center;
                    font-size: 18px;
                    vertical-align: middle;
                }
            }
        }

        .el-menu-item-group {
            .el-menu-item-group__title {
                padding: 0;
                display: none;
            }
        }

        .el-menu-item {
            min-width: auto;
            padding-left: 3.125rem !important;
            font-size: 0.875rem;

            img {
                width: 1.25rem;
                height: 1.25rem;
                margin-right: 0.3125rem;
            }

            i[class^="el-icon-"] {
                margin-right: 5px;
                width: 24px;
                text-align: center;
                font-size: 18px;
                vertical-align: middle;
            }
        }

        .el-submenu.el-menu-item {
            padding-left: 4.375rem !important;
        }

        .el-submenu.el-submenu.el-menu-item {
            padding-left: 5.625rem !important;
        }
    }

    &.collapsed {
        ::v-deep(.el-menu--collapse) {
            .el-submenu {
                .el-submenu__title {
                    span {
                        height: 0;
                        width: 0;
                        overflow: hidden;
                        visibility: hidden;
                        display: inline-block;
                    }
                }
            }
        }
    }
}

/* 响应式样式 */
@media screen and (max-width: 768px) {
    .menu {
        position: fixed;
        height: 100vh;
        z-index: 1000;
        left: 0;
        top: 0;
        box-shadow: 2px 0 8px rgba(0, 0, 0, 0.15);

        &.collapsed {
            transform: translateX(-80%);

            .collapse-btn {
                position: absolute;
                right: 0;
                top: 0;
                background-color: #333744;
                border-radius: 0 0 5px 0;
                width: 40px;
                height: 40px;
                display: flex;
                justify-content: center;
                align-items: center;
                padding: 0;
            }
        }
    }

    /* 启用整个页面的左右滑动 */
    body {
        overflow-x: auto;
        touch-action: pan-x;
    }
}
</style>
